/*
* 此文件主要放相关工具类方法
* */
const pfFunPrivateTool = {
  //二维码数组样式
  getFootBarCodeColStyle(ob) {
    let style = {display: 'inline-block', padding: '4px 0px'}
    if (!ob.col) ob.col = 12
    //宽度: 百分比
    let width = ob.col / 24 * 100 + '%'
    style.width = width
    style.maxWidth = width
    style.overflowX = 'hidden'

    if (ob.colStyle) {
      Object.keys(ob.colStyle).forEach(key => {
        style[key] = ob.colStyle[key]
      })
    }

    return style
  },
  //获取分页显示值
  getPageValue(pageNum, tableData, config) {
    if (config.printTemplate.configJson.pageFormat) {
      return config.printTemplate.configJson.pageFormat.replace('a', pageNum).replace(/(.*)b/, '$1' + Math.ceil(tableData.length / this.printerPageSize))
    }
    return pageNum + '/' + Math.ceil(tableData.length / this.printerPageSize)
  },
  getHeadStyle(ob, config) {
    let style = {paddingBottom: '0px', textAlign: 'center', width: '100%', marginLeft: '2%'}
    if (config.flagHeadBorder) { //表头也显示边框
      style.width = '92%'
      style.marginLeft = '13px'
    }
    return style
  },
  //获取共享行表头宽度
  getShareRowHeadStyle(ob, config) {
    let style = this.getHeadStyle(ob, config)
    let width = +style.width.replace('%', '')
    if (config.barcodes && config.barcodes.length > 0) {
      //左对齐宽度
      width -= this.getLeftShareBarCodeWidth(config)
      //右对齐宽度
      width -= this.getRightShareBarCodeWidth(config)
    }
    width -= 3
    style.width = width + '%'
    style.float = 'left'
    style.marginTop = '10px'
    style.marginLeft = '3%'
    return style
  },
  //获取左侧共享行宽度
  getLeftShareBarCodeWidth(config) {
    let width = 0
    let leftShareBarCode = config.barcodes.filter(barcode => barcode.flagShareRow && barcode.alignType == this.alignType.left)
    if (leftShareBarCode && leftShareBarCode.length) {
      let maxLeftWidth = leftShareBarCode.map(barcode => barcode.col).reduce((num1, num2) => {
        return num1 > num2 ? num1 : num2
      })
      if (maxLeftWidth > 24) {
        maxLeftWidth = 24
      }
      width = Math.ceil(maxLeftWidth * 100 / 24)
    }
    return width
  },
  //获取左侧共享行宽度
  getRightShareBarCodeWidth(config) {
    let width = 0
    let rightShareBarCode = config.barcodes.filter(barcode => barcode.flagShareRow && barcode.alignType == this.alignType.right)
    if (rightShareBarCode && rightShareBarCode.length) {
      let maxRightWidth = rightShareBarCode.map(barcode => barcode.col).reduce((num1, num2) => {
        return num1 > num2 ? num1 : num2
      })
      width = Math.ceil(maxRightWidth * 100 / 24)
    }
    return width
  },
  //表头表尾列样式
  getHeadFootColStyle(ob, index, config) {
    let style = {padding: '1px 0px', textAlign: 'left', display: 'inline-block'}
    if (!ob.col) {
      ob.col = 8 //默认为8
    }
    if (ob.col > 24) {
      ob.col = 24 //最大为24
    }
    if (ob.alignType == this.alignType.right) {
      style.float = 'right'
    }

    if (!config || !config.printTemplate) {
      throw Error('config.printTemplate不存在1')
    }

    if (config.printTemplate.configJson.flagHeadBorder && index != undefined) { //表头也显示边框
      style.border = '1px solid black'
      // style.width = '33%'
      // if (index > 0) {
      //   style.borderTop = '0px'
      // }
    }
    //宽度: 百分比
    let width = Math.floor(ob.col / 24 * 100) + '%'
    style.width = width
    style.maxWidth = width
    style.overflowX = 'hidden'

    if (ob.colStyle) {
      Object.keys(ob.colStyle).forEach(key => {
        style[key] = ob.colStyle[key]
      })
    }
    return style
  },

  //表头列标题样式
  getHeadFootColLabelStyle(ob, index, config) {
    let style = {
      fontWeight: 'bold',
      fontSize: '12px',
      width: this.headFootColLabelMax + 'px',
      textAlign: 'right'
    }
    if (ob.formation == this.upDown) { //上下结构的
      style.width = '100%'
    }
    if (ob.labelStyle) {
      Object.keys(ob.labelStyle).forEach(key => {
        style[key] = ob.labelStyle[key]
      })
    }
    if (ob.fontSize) {
      style.fontSize = ob.fontSize + 'px'
    }
    if (!config || !config.printTemplate) {
      throw Error('config.printTemplate不存在2')
    }
    if (config.printTemplate.configJson.flagHeadBorder || ob.formation == this.upDown) {
      style.display = 'inline-block'
      style.textAlign = 'center'
    }
    return style
  },

  //表格标题列样式
  getDataTableStyle() {
    let style = {
      borderCollapse: 'collapse',
      width: '96%',
      marginRight: 'auto',
      tableLayout: 'fixed',
      marginLeft: '-20px'
    }

    //三等份
    if (this.printerPageWidth == 243) style.width = '83%'
    return style
  },
  //表格标题列样式
  getTitleStyle(config) {
    let style = {textAlign: 'center', fontSize: '18px', fontWeight: 'bold'}
    //三等份
    if (this.printerPageWidth == 243) {
      style.width = '83%'
    }
    let shareBarCode = config.barcodes.filter(barcode => barcode.flagShareRow)
    if (!shareBarCode || shareBarCode.length == 0) {
      return style
    }
    //共享行时设置位置
    let rightShareBarCode = shareBarCode.filter(barcode => barcode.alignType == this.alignType.right)
    if (rightShareBarCode && rightShareBarCode.length > 0) {
      let rightCol = 0
      rightShareBarCode.forEach(barcode => {
        if (barcode.col > rightCol) {
          rightCol = barcode.col
        }
      })
      if (rightCol > 24) {
        rightCol = 24
      }
      if (rightCol > 0) {
        style.marginRight = Math.floor(rightCol * 100 / 24) + '%'
      }
    }
    let leftShareBarCode = shareBarCode.filter(barcode => barcode.alignType == this.alignType.left)
    if (leftShareBarCode && leftShareBarCode.length > 0) {
      let leftCol = 0
      leftShareBarCode.forEach(barcode => {
        if (barcode.col > leftCol) {
          leftCol = barcode.col
        }
      })
      if (leftCol > 24) {
        leftCol = 24
      }
      if (leftCol > 0) {
        style.marginLeft = Math.floor(leftCol * 100 / 24) + '%'
      }
    }
    return style
  },
  //是否显示主标题
  showTitle(pageNum, config) {
    console.log('showTitleconfig', config)
    if (!config || !config.printTemplate) {
      throw Error('config.printTemplate不存在3')
    }
    if (this.strings.isEmpty(config.printTemplate.title)) {
      return false
    }
    if (!this.titleEveryPage && pageNum != 1) {
      return false
    }
    return true
  },
  //是否显示副标题
  showSubTitle(pageNum, config) {
    if (!config || !config.printTemplate) {
      throw Error('config.printTemplate不存在4')
    }
    if (!config.printTemplate.configJson.showSubTitle) { //不显示副标题
      return false
    }
    if (!this.titleEveryPage && pageNum != 1) {
      return false
    }
    return true
  },
  //显示barcode
  showBarcode(pageNum, config) {
    if (!config.barcodes || config.barcodes.length == 0) {
      return false
    }
    if (!this.titleEveryPage && pageNum != 1) {
      return false
    }
    if (config.barcodes.filter(barcode => !barcode.flagShareRow).length == 0) { //都是共享行
      return false
    }
    return true
  },
  //显示共享行
  showShareRows(pageNum, alignType, config) {
    if (!config.barcodes || config.barcodes.length == 0) {
      return false
    }
    if (!this.titleEveryPage && pageNum != 1) {
      return false
    }
    if (config.barcodes.filter(barcode => barcode.flagShareRow && barcode.alignType == alignType).length == 0) { //没有共享行
      return false
    }
    return true
  },
  //是否显示小计
  showSubTotal(config) {
    if (config.sumFields == null || config.sumFields.length == 0) {
      return false
    }
    return true
  },
  //是否显示合计
  showTotal(pageNum, tableData) {
    if (pageNum == Math.ceil(tableData.length / this.printerPageSize)) {
      return true
    }
    return false
  },
  //获取副标题
  getSubTitle(row, config) {
    if (!config || !config.printTemplate) {
      throw Error('config.printTemplate不存在5')
    }
    if (config.pagebreakFields && config.pagebreakFields.length > 0) { //有分单的，以分单数据为准
      return config.pagebreakFields.map(field => config.columns.filter(column => column.name == field)[0].title + ':' + row[field]).join(',')
    }
    return this.getTitle(config.printTemplate.configJson.subTitle, config)
  },
  //表格标题列样式
  getSubTitleStyle(config) {
    let style = {textAlign: 'center', fontSize: '13px', fontWeight: 'bold'}

    //三等份
    if (this.printerPageWidth == 243) style.width = '83%'

    //共享行时设置位置
    let shareBarCode = config.barcodes.filter(barcode => barcode.flagShareRow)
    let rightShareBarCode = shareBarCode.filter(barcode => barcode.alignType == this.alignType.right)
    if (rightShareBarCode && rightShareBarCode.length > 0) {
      let rightCol = 0
      rightShareBarCode.forEach(barcode => {
        if (barcode.col > rightCol) {
          rightCol = barcode.col
        }
      })
      if (rightCol > 24) {
        rightCol = 24
      }
      if (rightCol > 0) {
        style.marginRight = Math.floor(rightCol * 100 / 24) + '%'
      }
    }

    let leftShareBarCode = shareBarCode.filter(barcode => barcode.alignType == this.alignType.left)
    if (leftShareBarCode && leftShareBarCode.length > 0) {
      let leftCol = 0
      leftShareBarCode.forEach(barcode => {
        if (barcode.col > leftCol) {
          leftCol = barcode.col
        }
      })
      if (leftCol > 24) {
        leftCol = 24
      }
      if (leftCol > 0) {
        style.marginLeft = Math.floor(leftCol * 100 / 24) + '%'
      }
    }
    return style
  },
  getShareBarCodeStyle(alignType, config) {
    let style = {textAlign: 'left', padding: '10px 0px', marginTop: '-10px'}
    let width = 0
    if (alignType == this.alignType.left) {
      width = this.getLeftShareBarCodeWidth(config)
    } else {
      width = this.getRightShareBarCodeWidth(config)
    }
    style.width = width + '%'
    style.float = alignType
    return style
  },
  //表格标题列样式
  getPageStyle(pageNum) {
    let style = {width: '100%', tableLayout: 'fixed', textAlign: 'center', marginTop: '-30px'}

    if (this.param.onlyForm) style.marginTop = '0px'
    //三等份
    if (this.printerPageWidth == 243) style.width = '83%'

    if (!this.titleEveryPage && pageNum != 1) {
      style.marginTop = '0px'
    }
    return style
  },
  //表格标题列样式
  getDataTableHeadThStyle(column, config) {
    let style = {border: '1px solid black', padding: '0px', fontSize: '12px', fontWeight: 'bold'}
    let title = column.title
    // style.minWidth = column.title.length * 15 + 'px'

    //宽度= 当前列宽度/所有需要打印的列的总宽度  * 纸张宽度
    let columnAllWidth = 0
    config.columns.forEach(column => {
      if (this.utilNum.isNum(column.width)) {
        columnAllWidth += column.width
      }
    })
    style.textAlign = column.alignType || 'center'
    if ( columnAllWidth <=0) {
      columnAllWidth = 100
    }
    let width = 'auto'
    if (column.width != width) {
      width = parseInt(column.width, 0) / columnAllWidth * 100
      style.width = width + '%'
      style.maxWidth = width + '%'
    } else {
      style.width = width
    }
    if (column.fontSize) {
      style.fontSize = column.fontSize + 'px'
    }
    return style
  },
  //表格数据列样式
  getDataTableBodyTdStyle(row, column) {
    let style = {border: '1px solid black', fontSize: '12px'}
    // let width = (ob.col/24*100)*this.printerPageWidth*this.mmRatePx
    if (!column.flagLineFeed) {
      style.overflow = 'hidden'
      style.whiteSpace = 'nowrap'
      style.textOverflow = 'unset'
    } else {
      style.wordBreak = 'break-all'
    }
    if (column.flagFontBold) {
      style.fontWeight = 'bold'
    }
    if (column.fontSize) {
      style.fontSize = column.fontSize + 'px'
    }
    if (column.alignType) {
      style.textAlign = column.alignType
    }
    if (this.param.rowHeight) {
      style.height = this.param.rowHeight + 'px'
    }
    return style
  },

  //表头表尾数据列样式
  getHeadFootColValueStyle(ob, index, config) {
    let style = {fontSize: '12px', textAlign: 'left'}
    if (ob.labelStyle) {
      Object.keys(ob.labelStyle).forEach(key => {
        style[key] = ob.labelStyle[key]
      })
    }
    if (ob.valueStyle) {
      Object.keys(ob.valueStyle).forEach(key => {
        style[key] = ob.valueStyle[key]
      })
    }
    if (ob.formation == this.upDown) { //上下结构的
      style.width = '100%'
    }
    if (ob.fontSize) {
      style.fontSize = ob.fontSize + 'px'
    }
    return style
  },
  getHeadLabel(ob) {
    if (ob.formation == this.upDown) {
      return ob.text
    }
    // 不显示冒号
    if (ob.flagHideColon && [1, true].includes(ob.flagHideColon) ) {
      return ob.text
    }
    return ob.text + ':'
  },
  //表头表尾数据
  getHeadFootValue(ob, config) {
    if (!ob.value) ob.value = config.formData[ob.name]
    return this.getPrintValue(ob, ob.value)
  },
  getPrintValue(column, value, row) {
    if (column.flagShowNegative && value && !isNaN(value)) { //转换为负数
      value = 0 - value
    }
    if (column.dateFmt && value) { //日期
      value = this.dates.formatToAnotherPattern(value, column.dateFmt)
    }
    if (column.dict) { //字典
      return this.utils.getDictLabel(value, column.dict, value, false)
    }
    if (column.expression) { //表达式
      return this.getExpression(value, column.expression, row)
    }
    return value
  },
  //获取列小计(合计),isSubTotal = true 表示小计
  getTotal(column, pageNum, tableData, isSubTotal, config) {
    let name = column.name
    if (this.strings.isEmpty(name)) {
      return ''
    }
    let typeKeyValue = ''
    if (config.sumFields == null || config.sumFields.length == 0) {
      return ''
    }
    if (config.sumFields.indexOf(name) < 0) {
      return ''
    }
    let sum = 0
    if (tableData != null && tableData.length > 0) {
      tableData.forEach((ob, index) => {
        if (!isSubTotal) {
          sum += Number(ob[name] || 0)
        } else if (index >= (pageNum - 1) * this.printerPageSize && index < pageNum * this.printerPageSize) {
          sum += Number(ob[name] || 0)
        }
      })
    }
    if (column.flagShowNegative && !isNaN(sum)) { //转换为负数
      sum = 0 - sum
    }
    return sum
  },
  getValue(column, row) {
    let value = row[column.name]
    return this.getPrintValue(column, value, row)
  },
  getTitle(title, config) { //获取标题
    if (this.strings.isBlank(title)) {
      return  ''
    }
    if (title.indexOf('{') < 0) {
      return title
    }
    try {
      const searchRegExp = new RegExp('{hospitalName}','g')
      title = this.strings.replaceAll(title, '{hospitalName}', global.settings.hospitalName)
      if (title.indexOf('{') < 0) {
        return title
      }
      if (config.head && config.head.length > 0) {
        config.head.forEach(ob => {
          if (title.indexOf('{' + ob.name + '}' > -1)) {
            title = this.strings.replaceAll(title, '{' + ob.name +'}', ob.text)
          }
        })
      }
    }catch (e) {
      console.error('getTitle 异常 title = ' + title)
      console.error(e)
    }
    return title
  },
  //获取表达式值
  getExpression(value, expression, row) {
    if (expression) {
      //默认值
      this.cpExpressionMap.forEach(map => {
        expression = this.strings.replaceAll(expression, '{' + map.key + '}', map.value)
      })
      //运算表达式
      let lambdaExpress = expression.match(/(add|sub|mul|div){1}\(.+\)/)
      if (lambdaExpress) { //add(filed1, filed2)
        let matchExp = lambdaExpress[0]
        let leftIndex = matchExp.indexOf('(')
        let middleIndex = matchExp.indexOf(',')
        let rightIndex = matchExp.indexOf(')')
        let calculateExp = matchExp.slice(0, leftIndex)
        let matchValue = null
        if (middleIndex == -1) { //包含,
          return expression
        }
        let leftExp = matchExp.slice(leftIndex + 1, middleIndex).trim()
        let rightExp = matchExp.slice(middleIndex + 1, rightIndex).trim()
        let leftValue = this.getExpValue(leftExp, row)
        let rightValue = this.getExpValue(rightExp, row)
        switch (calculateExp) {
        case 'add':
          matchValue = leftValue + rightValue
          break
        case 'sub':
          matchValue = leftValue - rightValue
          break
        case 'mul':
          matchValue = leftValue * rightValue
          break
        case 'div':
          matchValue = leftValue / rightValue
          break
        default:
          break
        }
        expression = expression.replace(matchExp, matchValue)
      }
      //图片
      //TODO 图片待实现
      // eslint-disable-next-line no-empty
      if (expression.indexOf('pic') > -1) {
      }
      return expression
    }
    return value
  },
  getExpValue(exp, row) {
    if (!row) {
      return exp
    }
    if (exp.indexOf('{') < 0 || exp.indexOf('}') < 0) {
      return exp
    }
    exp = this.strings.replaceAll(exp, '{', '')
    exp = this.strings.replaceAll(exp, '}', '')
    return row[exp] || exp
  },
  //转换分单数据
  getPagebreakData(responseData) {
    this.tableDatas = this.strings.funGroupBy(responseData, (item) => {
      return this.param.pagebreakFields.map(key => item[key])
    })
  },
  //转换分组数据
  getGroupData(tableData, config) {

    if (!tableData || tableData.length == 0) {
      return tableData
    }
    if (!config.groupFields || config.groupFields.length == 0) {
      return tableData
    }

    //获取分组的数据
    let groupData = this.strings.funGroupBy(tableData, (item) => {
      return config.groupFields.map(key => item[key])
    })
    if (!groupData || groupData.length == 0) {
      return tableData
    }
    //展示的数据
    let showData = []
    let sumFields = config.sumFields || []
    groupData.forEach(data => {
      //取每组的第一条数据，有合计的进行合计
      let firstData = data[0]
      Object.keys(firstData).forEach(key => {
        if (sumFields.includes(key)) {
          if (!isNaN(parseInt(firstData[key], 0))) {
            try {
              firstData[key] = this.utilNum.sum(data.map(d => d[key]))
            }catch (e) {
              this.utilMessage.error('计算分组合计失败(具体原因请看控制台)，字段: ' + key)
              console.error('计算分组合计失败(具体原因请看控制台)，字段: ' + key)
              console.error(e)
              throw Error('打印失败')
            }
          }
        }
      })
      showData.push(firstData)
    })
    return showData
  },
  //获取表头和表尾标题宽度，取最多标题的宽度
  getHeadFootColLabelMax() {
    if (this.headFootColLabelMax) return this.headFootColLabelMax
    let strMax = ''
    if (this.param.head && this.param.head.length > 0) {
      this.param.head.forEach(ob => {
        if (ob.text.length > strMax.length) strMax = ob.text
      })
    }
    // if(this.param.foot && this.param.foot.length>0) {
    //   this.param.foot.forEach(ob =>  {
    //     if(ob.text.length > strMax.length) strMax = ob.text
    //   })
    // }
    this.headFootColLabelMax = strMax.length * 15
  }
}
export default pfFunPrivateTool
